package com.sicheng.metadata.juc.线程通信.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Share {

    private int number = 0;

    //可重用锁
    private final ReentrantLock lock = new ReentrantLock();

    private final Condition condition = lock.newCondition();

    public void incr() {
        lock.lock();
        try {
            // 判断
            while (number != 0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 干活
            System.out.println(Thread.currentThread().getName() + "::" + ++number);
            // 通知
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void decr() {

        lock.lock();

        try {
            // 判断
            while (number != 1) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 干活
            System.out.println(Thread.currentThread().getName() + "::" + --number);
            // 通知
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
